﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CAUpdate.aspx.cs" Inherits="RN.ERP.Web.CA.CAUpdate" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="../Styles/skins/blue/css/style.css" rel="stylesheet" type="text/css" />
    <link href="../Styles/skins/blue/css/style_msg.css" rel="stylesheet" type="text/css" />
    <script src="../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript" src="../Scripts/iepngfix_tilebg.js"></script>
    <script src="../Scripts/xenroll.js" type="text/javascript"></script>
    <script src="../Scripts/pta.js" type="text/javascript"></script>
    <script src="../Scripts/calogin.js" type="text/javascript"></script>
    <object id="keyinfo" codebase="../Content/gksn.cab#Version=1,0,12,613" classid="clsid:12D390AD-D96D-4826-AA23-DC4D9456AB4D">
    </object>
    <object id="cenroll" codebase="../Content/itruscertctl.cab#Version=1,1,2013,801"
        classid="CLSID:DD2257CE-4FEE-455A-AD8B-860BEEE25ED6">
    </object>
    <object id="iTrusPTA" codebase="../Content/itruscertctl.cab#version=2,5,6,0" classid="clsid:F1F0506B-E2DC-4910-9CFC-4D7B18FEA5F9">
    </object>
    <script type="text/javascript">
        function refresh() {
            window.location.reload();
        }
        var keynum = 0, currentIndex = 0;
        var arrayCerts, allCerts;
        var certCountInKey = 0;
        var Entity;
        var EntityGuid;
        var keyid;
        $(function () {
            if (!window.ActiveXObject) { // 不是 IE
                $(".divMessage").html("请使用 IE 内核浏览器进行数字证书操作。");
                document.title = "不支持的浏览器";
                return;
            }
            if (navigator.userAgent.toLowerCase().indexOf('windows nt 6.2') > 0) {
                $(".divMessage").html('证书更新暂时不支持 Windows 8 操作系统');
                document.title = "不支持的操作系统";
                return;
            }
            // 天威插件加载检查
            if (cenroll.GenKeyFlags == null || iTrusPTA.Version == null || keyinfo.pkcs11_dll == null) {
                $(".divMessage").html("请首先安装浏览器提示的插件。");
                document.title = "未加载插件";
                return;
            }

            var Result = CheckDogCA();
            var str = Result.split(',');
            $('#cryptProv option').remove();
            findProviders($('#cryptProv')[0]);  // 初始化天威用的 CSP 列表

            var arrayIssuerDN = new Array(
            "C=CN, O=\"iTruschina Co., Ltd.\", OU=China Trust Network, OU=Terms of use at https://www.itrus.com.cn/ctnrpa (c)2007, CN=iTruschina CN Enterprise Individual Subscriber CA"
            , "CN=Flyedt Class 2 CA");
            allCerts = filterCerts(arrayIssuerDN, 0, "");  // 系统中的天威和自签证书（包括软证）
            arrayCerts = ExtendedFilter(allCerts);  // 过滤出硬件 Key 中的天威和自签证书

            document.title = "证书更新";
            if (str[0] == "0") {
                if (str[1] == "") {
                    $(".divMessage").html("请插入数字证书设备。");
                    return;
                }
                keyid = str[1];
                var patt1 = /CN=[^,\0]*/;
                var cn1 = patt1.exec(arrayCerts[0].subject);
                var cnval1 = cn1[0].replace('CN=', '');
                $("#hidName").val(cnval1);
                $.ajax({
                    url: "CAUpdate.aspx/ValidateKey",
                    data: "{ 'dogid':'" + str[1] + "','subid':'" + $("#hidId").val() + "','name':'" + $("#hidName").val() + "'}",
                    type: "post",
                    cache: false,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        var json = eval('(' + data.d + ')');
                        if (json.value) {
                            var dn1 = patt1.exec(arrayCerts[0].issuer);
                            var dnval1 = dn1[0].replace('CN=', '');
                            if (dnval1 != "iTruschina CN Enterprise Individual Subscriber CA") {
                                window.open("http://123.234.82.27/caman");
                                $(".divMessage").html("正在处理...");
                            }
                            else {
                                $("#winContent_Message").css("display", "none");
                                $("#winContent_SelCert").css("display", "");
                                Entity = json.mes.split("|")[0];
                                EntityGuid = json.mes.split("|")[1];
                                if (arrayCerts.length > 0) selectCert(0);
                            }
                        }
                        else {
                            $(".divMessage1").html(json.mes);
                            document.title = "验证失败";
                        }
                    }
                });
            }
            else {
                $(".divMessage").html(unescape(str[1]));
            }
        });
        var entityType;
        function selectCert(index) {
            if (index == null) index = 0;
            var currentIndex = index;
            if (index >= 0) {
                var objOldCert = arrayCerts[index]; //当前要更新的证书
                var snver = getCertVersion(objOldCert);
                var cnname = getCertSubjectField(objOldCert, 'CN');
                certCountInKey = 0;
                for (i = 0; i < allCerts.length; i++) {
                    if (allCerts[i].CSP == 'EnterSafe ePass3003 CSP v1.0' && allCerts[i].Issuer == objOldCert.Issuer) {
                        if (getCertName(allCerts[i]) == cnname && getCertVersion(allCerts[i]) == snver) certCountInKey++;
                    }
                }
                entityType = arrayCerts[index].subject.indexOf('办公室（个人）') > 0 ? true : false;
                $(".kn").html(keyid);
                var patt = /CN=[^,\0]*/;
                var cn = patt.exec(arrayCerts[index].subject);
                var cnval = cn[0].replace('CN=', '');
                $(".cn").html(cnval);
                var dn = patt.exec(arrayCerts[index].issuer);
                var dnval = dn[0].replace('CN=', '');
                $(".dn").html(dnval);
                var dateFrom = new Date(arrayCerts[index].validFrom);
                var dateTo = new Date(arrayCerts[index].validTo);
                var updatedays = (dateTo.getTime() - new Date().getTime()) / 86400000;
                //updateflag = 2;
                updateflag = (updatedays > 30 && (isItrusCert(objOldCert) && certCountInKey > 1 || isFlyCert(objOldCert))) ? 1 : 2;
                $(" .valid").html("从 " + (dateFrom.getYear() + "-" + (dateFrom.getMonth() + 1) + "-" + dateFrom.getDate()) + " 到 "
                + (dateTo.getYear() + "-" + (dateTo.getMonth() + 1) + "-" + dateTo.getDate())
                    + ' ' + (updateflag == 1 ? "(无需更新)" : "<span style='color:red'>(需要更新或升级)</span>"));
                if (updateflag == 1) {
                    $(".update").css("display", "none");
                }
                else if (dnval == "iTruschina CN Enterprise Individual Subscriber CA") {
                    $(".refresh").css("display", "none");
                }
            }
        }
        // 更新天威证书
        function updateRequest_Itrus(index) {
            $(".divMessage").html("正在处理...");
            $("#winContent_SelCert").hide();
            $("#winContent_Message").show();
            //win3.content("正在处理。。。").center().title("请稍候").open();
            if (index == -1)
                return false;
            var objOldCert = arrayCerts[index]; //当前要更新的证书

            /**
            * genRenewCSR 更新证书，生成更新证书的证书签名请求
            */
            var csr = genRenewCSR($('#cryptProv')[0], 1, objOldCert);
            //var csr = certCountInKey == 1 ? genEnrollCSR($('#cryptProv')[0], 1) : genRenewCSR($('#cryptProv')[0], 1, objOldCert);

            if (csr.length == 0) {
                return false;
            }

            /**
            * signCSR 更新证书时需要调用，对更新证书的CSR
            */
            var csrSignedData = "";
            if (certCountInKey > 1) {
                csrSignedData = signCSR(objOldCert, csr);
                if (csrSignedData.length == 0) {
                    return false;
                }
            }
            $.ajax({
                url: "CAUpdate.aspx/UpdateCert",
                data: "{ 'csr':'" + csr + "','csrSigned':'" + csrSignedData + "','certSN':'" + objOldCert.SerialNumber
                    + "','cert':'" + objOldCert.GetEncodedCert(2) + "','entity':'" + Entity + "','count':'" +
                     certCountInKey + "','raEntity':'" + entityType + "','KeySN':'" + keyid + "','EntityGuid':'" +
                      EntityGuid + "','EntityName':'" + $("#hidName").val() + "','subid':'" + $("#hidId").val() + "'}",
                type: "post",
                cache: false,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    var json = eval('(' + data.d + ')');
                    if (json.value == 0) {
                        DoInstallCert(json.mes);
                    }
                    else {
                        $("#winContent_Message").css("display", "");
                        $("#winContent_SelCert").css("display", "none");
                        $(".divMessage").html("证书更新过程中发生错误。<br/>错误原因：" +
                        json.mes.split("|")[1] + "<br/>");
                        document.title = "通讯错误";
                    }
                },
                error: function (xhr, err) {
                    $("#winContent_Message").css("display", "");
                    $("#winContent_SelCert").css("display", "none");
                    $(".divMessage").html("证书更新过程中发生错误。<br/>错误信息：" + xhr.status +
                     "<br/>");
                    document.title = "通讯错误";
                }
            });
            return true;
        }
        function DoInstallCert(resp) {
            var str = resp.split("|");
            if (str[1].split(":")[1].length > 0) {
                if (InstallCert(str[1].split(":")[1])) {
                    if (str[3].split(":")[1].length > 0) {
                        cenroll.containerName = "";
                        cenroll.KeySpec = 1;
                        cenroll.writeCertToCSP = true;

                        var req0 = str[3].split(":")[1].toString();
                        var req1 = req0.replace(/\&/g, '&amp;');
                        installCertKmc(str[6].split(":")[1], "", str[2].split(":")[1], str[2].split(":")[1],
                        str[2].split(":")[1], req1, str[4].split(":")[1], str[5].split(":")[1]);
                    }
                    //UpdateCAStatus(ordid);
                    $("#winContent_Message").css("display", "");
                    $("#winContent_SelCert").css("display", "none");
                    document.title = "更新成功";
                    $(".divMessage").html("您的数字证书已经成功更新");
                }
            }
        }
        function ExtendedFilter(certs) {
            var newCerts = new Array();
            var retCerts = new Array();
            var names = new Array();
            for (i = 0; i < certs.length; i++) {
                if (certs[i].CSP == 'EnterSafe ePass3003 CSP v1.0'
                && (certs[i].Issuer.indexOf("CN=Flyedt Class 2 CA") >= 0 || (certs[i].KeyUsage & 0x80)))
                    newCerts.push(certs[i]);
            }
            var founded;
            for (j = 0; j < newCerts.length; j++) {
                var snver = getCertVersion(newCerts[j]);
                var cnval = getCertName(newCerts[j]);
                founded = false;
                for (n = 0; n < names.length; n++) {
                    //alert(cnval + ' ' + names[n]+' '+(cnval == names[n]));
                    if (cnval == names[n]) {
                        founded = true;
                        break;
                    }
                }
                if (founded) continue;
                names.push(cnval);
                for (k = 0; k < newCerts.length; k++) {
                    if (getCertName(newCerts[k]) == cnval && getCertVersion(newCerts[k]) > snver)
                        snver = getCertVersion(newCerts[k]);
                }
                for (k = 0; k < newCerts.length; k++) {
                    if (getCertName(newCerts[k]) == cnval && getCertVersion(newCerts[k]) == snver)
                        retCerts.push(newCerts[k]);
                }
            }
            return retCerts;
        }
        function isFlyCert(cert) {
            return cert.Issuer.indexOf('Flyedt Class 2 CA') >= 0;
        }
        function isItrusCert(cert) {
            return cert.Issuer.indexOf('iTruschina Co., Ltd') >= 0;
        }
        function getCertName(cert) {
            var pattCN = /CN=[^,\0]*/;
            var cn = pattCN.exec(cert.subject);
            return cn[0].replace('CN=', '');
        }
        function getCertVersion(cert) {
            var pattSN = /SN=[^,\0]*/;
            var sn = pattSN.exec(cert.subject);
            if (sn == null) return 0;
            var snval = sn[0].replace('SN=', '');
            var snarray = snval.split('*');
            return snarray.length == 1 ? 0 : (snarray[1] * 1);
        }
        function getCertSubjectField(cert, field) {
            var patt, cn, cnval;
            patt = new RegExp(field + '=[^,\0]*');
            cn = patt.exec(cert.subject);
            cnval = cn == null ? '' : cn[0].replace(field + '=', '');
            return cnval;
        }

    </script>
    <style type="text/css">
        .IE6png
        {
            behavior: url("../Scripts/iepngfix.htc");
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div id="winContent_Message" style="clear: both; font-family: 'Microsoft Yahei';">
            <center>
                <div class="divMessage" style="margin-top: 30px; font-weight: bold; font-size: 20px;">
                    <strong>证书：</strong><select class="CertList t-input" name="CertList2">
                    </select>
                    <div class="divMessage1" style="padding-top: 10px;">
                    </div>
                </div>
                <div class="icon01 IE6png" style="float: none; margin-top: 10px;">
                    <a href="javascript:void(0);" onclick="refresh();">刷新</a>
                </div>
            </center>
        </div>
        <div id="winContent_SelCert" style="display: none; padding-top: 10px; clear: both;
            font-family: 'Microsoft Yahei;'">
            <center>
                <table width="80%" border="0" cellspacing="0" cellpadding="0" class="tab">
                    <tr>
                        <td width="40%" bgcolor="#f2f2f2">
                            <strong>证书</strong>
                        </td>
                        <td style="text-align: left">
                            <select class="CertList t-input" name="CertList">
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td width="30%" bgcolor="#f2f2f2">
                            <strong>设备号</strong>
                        </td>
                        <td class="kn" style="text-align: left">
                        </td>
                    </tr>
                    <tr>
                        <td width="30%" bgcolor="#f2f2f2">
                            <strong>使用者</strong>
                        </td>
                        <td class="cn" style="text-align: left">
                        </td>
                    </tr>
                    <tr>
                        <td width="30%" bgcolor="#f2f2f2">
                            <strong>签发者</strong>
                        </td>
                        <td class="dn" style="text-align: left">
                        </td>
                    </tr>
                    <tr>
                        <td width="30%" bgcolor="#f2f2f2">
                            <strong>有效期</strong>
                        </td>
                        <td class="valid" style="text-align: left">
                        </td>
                    </tr>
                </table>
                <div class="icon01 IE6png refresh" style="float: none; margin-top: 10px;">
                    <a href="javascript:void(0);" onclick="refresh();">刷新</a>
                </div>
                <div class="icon01 IE6png update" style="float: none; margin-top: 10px;">
                    <a href="javascript:void(0);" onclick="updateRequest_Itrus(0);">更新</a>
                </div>
            </center>
        </div>
        <div style="display: none">
            <select id="cryptProv" style="display: none">
            </select>
        </div>
        <telerik:RadScriptManager ID="RadScriptManager1" runat="server">
        </telerik:RadScriptManager>
        <telerik:RadWindowManager ID="RadWindowManager1" runat="server">
        </telerik:RadWindowManager>
        <asp:HiddenField ID="hidId" runat="server" />
        <asp:HiddenField ID="hidName" runat="server" />
    </div>
    </form>
</body>
</html>
